import axios from 'axios'
import store from '../store'
import {
  Message
} from 'element-ui'
import {
  getToken
} from '@/utils/getToken'

let BaseURL
if (process.env.NODE_ENV === 'development' && process.env.VUE_APP_PROXY_BASEURL && process.env.VUE_APP_PROXY_BASEURL !== '') {
  BaseURL = process.env.VUE_APP_PROXY_BASEURL
} else {
  BaseURL = process.env.VUE_APP_BASEURL || location.origin
}

const timeout = 15 * 1000

// 创建axios实例
const service = axios.create({
  baseURL: BaseURL + '/api/',
  timeout: timeout
})

// 特殊处理超时延长接口
const timeout2 = 2 * 15 * 1000
const SpecialTimeoutInterface = []

// request 请求拦截器
service.interceptors.request.use(config => {
  const Token = getToken()

  if (Token) {
    config.headers = {
      Authorization: Token
    }
  }

  const requestUrl = config.url

  // 特殊处理超时接口
  if (SpecialTimeoutInterface.indexOf(requestUrl) > -1) {
    config.timeout = timeout2
  }

  if (config.method === 'get') {
    let urlParams = ''
    if (config.data && JSON.stringify(config.data) !== '{}') {
      const data = config.data
      for (const key in data) {
        if (data[key] && data[key] !== '') {
          urlParams += key + '=' + data[key] + '&'
        }
      }
      // 去掉最后的 &
      urlParams = urlParams.substring(urlParams.length - 1, 0)

      config.url = config.url + '?' + urlParams
    }
  }

  if (config.data === undefined || config.data === '') {
    config.data = {}
  }

  return config
}, error => {
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    // 可正常返回的 codeList
    const res = response.data
    const codeList = [100, '100', 200]
    if (codeList.indexOf(res.code) > -1) {
      return res
    } else {
      statusCodeError(res, 1)
      return Promise.reject(res)
    }
  }, error => {
    if (error.message.includes('timeout')) {
      Msg('请求超时')
      return Promise.reject(error)
    }
    if (error.response) {
      statusCodeError(error.response)

      return Promise.reject(error)
    } else {
      Msg(error.message + '，系统异常!')
      return Promise.reject(error)
    }
  }
)

const statusCodeError = (errorInfo, type) => {
  // type 错误类型 1 服务端返回错误 其他http状态码错误
  let status = ''
  let statusText = ''
  let serviceErrMsg = ''
  if (type === 1) {
    // status = errorInfo.code + ' ' || errorInfo.status
    console.log('后端服务正常抛出错误')
    console.log(errorInfo)
    serviceErrMsg = errorInfo.message || errorInfo.error
  } else {
    // 其他http状态码错误
    const err = {
      url: errorInfo.config.url,
      method: errorInfo.config.method,
      paramsData: errorInfo.config.data,
      errData: errorInfo.data
    }
    console.log('后端服务异常抛出错误')
    console.log(err)
    status = errorInfo.status
    statusText = ' ' + errorInfo.statusText
    serviceErrMsg = errorInfo.data.error ? '， ' + errorInfo.data.error : ''
  }

  if (errorInfo.code === 202 || errorInfo.status === 202) {
    // 登录失效
    setTimeout(() => {
      store.dispatch('loginout')
      window.location.href = '/#/login'
    }, 1 * 1000)
  }
  Msg(status + statusText + serviceErrMsg)
}

// msg error
const Msg = (msg, config) => {
  let defaultConfig = {
    showClose: true,
    type: 'error',
    duration: 3 * 1000
  }
  if (config) {
    defaultConfig = {
      ...config
    }
  }
  Message({
    message: msg,
    type: defaultConfig.type,
    duration: defaultConfig.duration,
    showClose: defaultConfig.showClose
  })
}

export default service
